//
//  JXAddressListController.m
//  JiaoX
//
//  Created by yinqy on 15/1/16.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//

#import "JXAddressListController.h"
#import "AddNewAddressView.h"
#import "SelfDataTool.h"
#import "AddressItemCell.h"
#import "JXAddressAddController.h"

@interface JXAddressListController ()<AddNewAddressViewDelegate,AddressItemViewDelegate>
{
    NSUInteger currentDefaultAdesIndex;
}
@property (nonatomic,strong)NSMutableArray *adesItemFrameArray;
@property (nonatomic,weak) AddNewAddressView *addNewView;

@end

@implementation JXAddressListController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle:@"地址管理"];
    
    self.adesItemFrameArray = [NSMutableArray array];
    UIView *view = self.navigationItem.leftBarButtonItem.customView;
    if ([view isKindOfClass:[UIButton class]]) {
        [((UIButton *)view) removeTarget:self.navigationController action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
        [((UIButton *)view) addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    }
    
    AddNewAddressView *addNewView =[[AddNewAddressView alloc]init];
    addNewView.delegate = self;
    self.addNewView = addNewView;
    [self.tableView setTableHeaderView:addNewView];
    [self.tableView setTableFooterView:[[UIView alloc]init]];
}

-(void)requestData{
    [SelfDataTool getAddressListSuccess:^(AddressDetailList *result) {
        if ([Utils isBlankString:result.data]) {
            [self setFramesWithData:result];
        }else{
            [DialogUtils showTipsWithView:self.navigationController.view String:result.data];
        }
    } failure:^(NSError *error) {
        [DialogUtils showTipsWithView:self.navigationController.view String:@"加载失败"];
    }];
}

-(void)setFramesWithData:(AddressDetailList *)result{
    [self.adesItemFrameArray removeAllObjects];
    for (int i=0; i<result.adresList.count; i++) {
        AddressItemFrame *frame = [[AddressItemFrame alloc]init];
        AddressDetail *detail = result.adresList[i];
        if (detail.defaultAdres) {
            currentDefaultAdesIndex = i;
        }
        [frame setDetail:detail];
        [self.adesItemFrameArray addObject:frame];
    }

    [self.tableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.adesItemFrameArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AddressItemCell *cell = [AddressItemCell cellWithTableView:tableView];
    cell.addressCellView.tag = indexPath.row;
    cell.addressCellView.delegate = self;
    [cell setAddressItemframe:self.adesItemFrameArray[indexPath.row]];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    AddressItemFrame *frame =self.adesItemFrameArray[indexPath.row];
    return frame.selfFrame.size.height;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    AddressItemFrame *newframe =self.adesItemFrameArray[indexPath.row];
    if(!newframe.detail.defaultAdres){
        newframe.detail.defaultAdres = 1;
        AddressItemFrame *oldframe =self.adesItemFrameArray[currentDefaultAdesIndex];
        oldframe.detail.defaultAdres = 0;
        currentDefaultAdesIndex = indexPath.row;
    }
    
    [self.tableView reloadData];
    
    if (_fromAccountCenter) {
        if ([_delegate respondsToSelector:@selector(setAddressDetailInfo:)]) {
            [_delegate setAddressDetailInfo:newframe.detail];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

-(void)back{
    if (_fromAccountCenter) {
        if ([_delegate respondsToSelector:@selector(setAddressDetailInfo:)]) {
            //遍历，取出选中的那一项
            AddressItemFrame *newframe = nil;
            for (AddressItemFrame *frame in self.adesItemFrameArray) {
                if (frame.detail.defaultAdres) {
                    newframe = frame;
                    break;
                }
            }
            if (newframe) {
                [_delegate setAddressDetailInfo:newframe.detail];
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
        [self requestData];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    AddressItemFrame *frame = [_adesItemFrameArray firstObject];
    if (_adesItemFrameArray.count>0 && frame.detail.defaultAdres==0) {
        [self setDefaultAddress];
    }
}

-(void)setDefaultAddress{
    AddressItemFrame *frame = _adesItemFrameArray[currentDefaultAdesIndex];
    AddressDetail *detail = frame.detail;
    [SelfDataTool addAddressWithAddressee:detail.addressee phoneCode:detail.phoneCode provinceId:detail.provinceIdStr cityId:detail.cityIdStr areaId:detail.areaIdStr detailAdres:detail.detailAdres addressId:detail.addressId success:nil failure:nil];
}

-(void)viewDidLayoutSubviews
{
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,JXPublicInset,0,0)];
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,JXPublicInset,0,0)];
    }
}

-(void)editBtnClick:(NSInteger)index{
    AddressItemFrame *newframe =self.adesItemFrameArray[index];
    JXAddressAddController *addCtrl = [[JXAddressAddController alloc]init];
    addCtrl.addressDetails = newframe.detail;
    [self.navigationController pushViewController:addCtrl animated:YES];
}

-(void)deleteBtnClick:(NSInteger)index{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"确定删除本条地址？" message:@"" delegate: self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
    alert.tag = index;
    [alert show]; //显示退出对话框
    JXLog(@"deleteBtnClick%ld",(long)index);
}

-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {     // and they clicked OK.
        //执行删除地址操作
        AddressItemFrame *newframe =self.adesItemFrameArray[alertView.tag];
        MBProgressHUD *HUD = [DialogUtils showLoadingWithView:self.navigationController.view];
        [SelfDataTool deleteAddressWithID:newframe.detail.addressId success:^(JXBaseResponse *result) {
            [HUD hide:YES];
            if([Utils isBlankString:result.data]){
                [DialogUtils showTipsWithView:self.navigationController.view String:@"删除成功"];
                [self.adesItemFrameArray removeObjectAtIndex:alertView.tag];
                if (alertView.tag == currentDefaultAdesIndex) {
                    //删除的是默认地址
                    if(self.adesItemFrameArray.count){
                        AddressItemFrame *tempFrame = [self.adesItemFrameArray firstObject];
                        tempFrame.detail.defaultAdres = 1;
                        currentDefaultAdesIndex = 0;
                        [self setDefaultAddress];
                    }else{
                        currentDefaultAdesIndex--;
                    }
                }
                [self.tableView reloadData];
            }else{
                //删除失败
                [DialogUtils showTipsWithView:self.navigationController.view String:result.data];
            }
        } failure:^(NSError *error) {
            [HUD hide:YES];
            //删除失败
            [DialogUtils showTipsWithView:self.navigationController.view String:@"删除失败"];
        }];
    }
}

-(void)selectBtnClick:(UIButton *)btn index:(NSInteger)index{
    if(btn.selected)
        return;
    AddressItemFrame *newframe =self.adesItemFrameArray[index];
    newframe.detail.defaultAdres = 1;
    
    AddressItemFrame *oldframe =self.adesItemFrameArray[currentDefaultAdesIndex];
    oldframe.detail.defaultAdres = 0;
    
    currentDefaultAdesIndex = index;
    
    [self.tableView reloadData];
}

/**
 *  新增地址点击
 */
- (void)addNewAddressBtnClick{
    JXAddressAddController *ctrl = [[JXAddressAddController alloc]init];
    [self.navigationController pushViewController:ctrl animated:YES];
}

-(BOOL)shouldLogin{
    return YES;
}
@end
